package com.Cfeng.XiaohuanChat.controller;

import com.Cfeng.XiaohuanChat.domain.Resp;
import com.Cfeng.XiaohuanChat.entity.ChatUser;
import com.Cfeng.XiaohuanChat.entity.UserNote;
import com.Cfeng.XiaohuanChat.service.ChatUserService;
import com.Cfeng.XiaohuanChat.service.UserNoteService;
import com.Cfeng.XiaohuanChat.util.AddressUtil;
import com.Cfeng.XiaohuanChat.util.BaiduMapGeoUtil;
import com.Cfeng.XiaohuanChat.util.IpUtils;
import com.Cfeng.XiaohuanChat.util.WeatherUtil;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/8/7
 * 主要就是进行路由跳转
 */

@Controller
@RequestMapping("/sys")
@Slf4j
@RequiredArgsConstructor
public class SystemController {

    private final ChatUserService chatUserService;

    private final UserNoteService userNoteService;

    @RequestMapping("/toIndex")
    public ModelAndView toIndex() {
//      注意这里是登录成功后默认跳转页面，还不能使用Principal对象
        ChatUser chatUser = chatUserService.queryUser(SecurityContextHolder.getContext().getAuthentication().getName());
        chatUser.setUserHeaderImg("/" + chatUser.getUserHeaderImg());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("chatUser",chatUser);
        modelAndView.setViewName("main");
        return modelAndView;
    }

    /**
     * 可以直接使用Principal对象【容器中有】登录之后
     */
    @RequestMapping("/toChat")
    public ModelAndView toChat(Principal principal) {
        //表示欢迎登录
        ChatUser chatUser = chatUserService.queryUser(principal.getName());
        chatUser.setUserHeaderImg("/" + chatUser.getUserHeaderImg());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("chatUser",chatUser);
        modelAndView.setViewName("chat");
        return modelAndView;
    }

    @RequestMapping("/toUser")
    public ModelAndView toUser(Principal principal) {
        //显示个人信息,提供修改
        ModelAndView modelAndView = new ModelAndView();
        String username = principal.getName();
        ChatUser user = chatUserService.queryUser(username);
        if(Objects.isNull(user)) {
            throw new RuntimeException("出错了,请稍后重试");
        }
        //模板中显示图片只要放在路径中就可以，所以将名称加上路径,这里给一个绝对路径，因为一般只会找寻src
        //配置locations之后就可以在其目录下寻找,加上/ 就可以寻找到，资源路径是相对此controller，找不到
        user.setUserHeaderImg("/" + user.getUserHeaderImg());
        modelAndView.addObject("chatUser",user);
        modelAndView.setViewName("userInfo");
        return modelAndView;
    }

    @RequestMapping("/toNote")
    public ModelAndView toNote(Principal principal) {
        //需要返回的数据包括用户，以及用户所有的笔记信息
        ChatUser chatUser = chatUserService.queryUser(principal.getName());
        chatUser.setUserHeaderImg("/" + chatUser.getUserHeaderImg());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("chatUser",chatUser);
        modelAndView.addObject("userNoteList",chatUser.getUserNoteList());
        modelAndView.addObject("noteNumber",chatUser.getUserNoteList().size());
        modelAndView.setViewName("note");
        return modelAndView;
    }

    @RequestMapping("/toNoteEdit")
    public String toNoteEdit() {
        return "noteEdit";
    }

    @GetMapping("/updateNote/{noteId}")
    public ModelAndView toUpdateNote(@PathVariable Long noteId) {
        ModelAndView modelAndView = new ModelAndView();
        UserNote userNote = userNoteService.getNote(noteId);
        modelAndView.addObject("note",userNote);
        modelAndView.setViewName("noteUpdate");
        return modelAndView;
    }

    @GetMapping("/toFile")
    public ModelAndView toFileIndex(Principal principal) {
        ModelAndView modelAndView = new ModelAndView();
        ChatUser chatUser = chatUserService.queryUser(principal.getName());
        chatUser.setUserHeaderImg("/" + chatUser.getUserHeaderImg());
        modelAndView.addObject("chatUser",chatUser);
        //放其余的
        modelAndView.setViewName("fileIndex");
        return modelAndView;
    }

    @RequestMapping("/welcome")
    public ModelAndView welcome(Principal principal) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("chatUser",chatUserService.queryUser(principal.getName()));
        modelAndView.setViewName("welcome");
        return modelAndView;
    }

    @RequestMapping("/toAdmin")
    public ModelAndView toAdmin(Principal principal) {
        ModelAndView modelAndView = new ModelAndView();
        //放入各种数据
        ChatUser admin = chatUserService.queryUser(principal.getName());
        admin.setUserHeaderImg("/" + admin.getUserHeaderImg());
        modelAndView.addObject("admin",admin);
        modelAndView.setViewName("admin");
        return modelAndView;
    }

    //测试显示登录用户的地址信息,都可以访问，不需要登录
    @PermitAll
    @RequestMapping("/getRegion")
    @ResponseBody
    public Resp<String> getRegion(HttpServletRequest request) {
        //使用IpUtils获取IP
        String ip = IpUtils.getIpAddr(request);
        log.info("访问的IP为{}",ip);
        if(StringUtils.isNullOrEmpty(ip)) {
            return Resp.failed("ip不存在");
        }
        return Resp.ok(AddressUtil.getRealAddressByIP(ip));
    }

    //测试显示登录用户的经纬度的地址信息
    @RequestMapping("/getAddress")
    @ResponseBody
    public Resp<String> getAddress(String longitude, String latitude) {
        //查询的结果
        String address = BaiduMapGeoUtil.getAddressInfoByLngAndLat(longitude, latitude);
        String city = (String) JSONObject.parseObject(address).get("city");
        return Resp.ok(WeatherUtil.getWheatherByCity(city));
    }

    //获取错误消息
    @RequestMapping("/getErrorMessage")
    @ResponseBody
    public Resp<Object> getErrorMessage(HttpSession session) {
        return Resp.ok(session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION"));
    }

}
